package com.lvmama.pangolin.timer.processor;



import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.lvmama.pangolin.busi.config.ConfigManager;
import com.lvmama.pangolin.common.IPTools;
import com.lvmama.pangolin.entity.IP;
import com.lvmama.pangolin.service.IPService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.util.SpringContextUtil;

/**
 * 
* @ClassName: IPValidConfirm 
* @Description: TODO 定时扫描验证无效IP，并删除无效IP，后续若引入redis，支持数据同步redis
* @author yuanchi
* @date 2017年2月23日 下午5:03:23
 */
public class IPValidConfirm extends CommonJob {

	@Autowired
	private IPService ipService;
	
	private Logger logger = Logger.getLogger(IPValidConfirm.class);
	
	@Override
	public void runJob(JobExecutionContext context, String parameter)
	{
		try
		{
			logger.info("IP可用性验证开始...");
			if(ipService == null)
			{
				ipService = (IPService) SpringContextUtil.getBean(IPService.class);
			}
			int limit = 500;
			int size = limit;
			int id = 0;
			while (size == limit)
			{
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("available", 1);
				param.put("limit_num", limit);
				param.put("id", id);
				
				List<IP> ipList =  ipService.queryIPOrderByid(param);
				if(ipList != null && !ipList.isEmpty())
				{
					size = ipList.size();
					boolean flag = false;
					for (IP ipVo : ipList)
					{
						try
						{
							id = ipVo.getId();
							String filterKey = ConfigManager.getInstance().getParamValue("PROXY_IP_FILTER_CONFIG", "PROXY_IP_FILTER_CONFIG", "true");
							flag = IPTools.checkIPValid(ipVo.getIp(), ipVo.getIp_port(),2000,filterKey);
							if(!flag)
							{
//								ipService.updateIPStatusByid(ipVo);
								ipService.deleteUnvalidIP(ipVo);
								logger.info("删除的IP为："+ipVo.toString());
							}
							
						}catch(Exception e)
						{
							logger.error("验证更新IP状态失败!",e);
						}
						
						
					}
					
				}
				else
				{
					size = 0;
				}
				
			}
			try
			{
				IP ipp = new IP();
				ipp.setAvailable(0);
//				ipp.setInsert_time(new Date());
				int deleteNum = ipService.deleteUnvalidIP(ipp);
				logger.info("周期删除无效IP数量：" + deleteNum);
				
			}catch(Exception e)
			{
				throw new Exception ("删除无效IP异常！",e);
			}
			
			logger.info("IP可用性验证开始结束......");
			
		}catch (Exception e)
		{
			logger.error("验证IP状态失败!",e);
		}
		
		
		
	}

}
